// 引入运行sql的插件和防止sql 注入的插件
const { exec, escape } = require('../db/mysql')

// 用户信息列表
const listUser = (role) => {
    let sql = ``
    if(role === 1){
        sql = `select user_id,user_email,user_role,user_create_time from user where user_role<${role} and user_is_deleted=0;`
    }else{
        sql = `select * from user;`
    }
    console.log(sql);
    return exec(sql).then(data => {
        // console.log(data);
        return data
    })
}

// 查询用户信息
const searchUser = (role,type,input) => {
    input = escape(input)
    let sql = ``
    if(role >1 ){
        sql = `select * from user where ${type}=${input};`
    }else{
        if(role > 0){
            sql = `select user_id,user_email,user_role,user_create_time from user where ${type}=${input} and user_role<${role} and user_is_deleted=0;`
        }else{
            sql = `select user_id,user_email,user_role from user where user_id=${input} and user_role=${role};`
        }
    }
    console.log(sql)
    return exec(sql).then(data => {
        console.log(data)
        data.errno = 0
        return data || {}
    }).catch(err => {
        err.errno = 1
        return err
    })
}

// 用户信息新建
const newUser = (id,password,email,role,time) => {
    const sql = `insert into user (user_id,user_password,user_email,user_role,user_create_time,user_update_time) values('${id}','${password}','${email}','${role}','${time}','${time}');`
    console.log(sql);
    return exec(sql).then(data => {
        // console.log(data)
        /*
        OkPacket {
          fieldCount: 0,
          affectedRows: 1,
          insertId: 0,
          serverStatus: 2,
          warningCount: 0,
          message: '',
          protocol41: true,
          changedRows: 0
        }
        */
        data.errno = 0
        return data
    }).catch(err => {
        err.errno = 1
        return err
    })
}

// 修改用户信息
const updateUser = (role, id,type,input) => {
    const sql =`update user set ${type}='${input}' where user_id='${id}';`
    console.log(sql);
    return exec(sql).then(data => {
        // console.log(data)
        data.errno = 0
        return data
    }).catch(err => {
        err.errno = 1
        return err
    })
}

// 删除用户信息
const deleteUser = (id) => {
    const sql = `delete from user where user_id='${id}';`
    console.log(sql);
    return exec(sql).then(data => {
        // console.log(data)
        /*
        OkPacket {
          fieldCount: 0,
          affectedRows: 1,
          insertId: 0,
          serverStatus: 2,
          warningCount: 0,
          message: '',
          protocol41: true,
          changedRows: 0
        }
        * */
        return data
    })
}

module.exports = {
    searchUser,
    listUser,
    newUser,
    updateUser,
    deleteUser
}